import {Request, Response} from 'express';

let isListening = false;

export function CatchAsyncError() {
    return (req: Request, res: Response, next: (err?: any) => any) => {
        if (isListening) return next();

        process.on('uncaughtException', (err: Error) => {
            res.status(500).json({message: err.message});
        });
        process.on('unhandledRejection', (err: Error) => {
            res.status(500).json({message: err.message});
        });

        isListening = true;
        next();
    };
}

export function CatchSyncError() {
    return (error: Error, req: Request, res: Response, next: (err?: any) => any) => {
        res.status(500).json({message: error.message});
    };
}
